import axios from 'axios';

const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1';
const API_KEY = "sk-f255887206dd4dd7a0b22d6b350b6b47"; // 从环境变量获取

const deepseekApi = axios.create({
  baseURL: DEEPSEEK_API_URL,
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  }
});

export default {
  /**
   * 获取聊天回复
   * @param {Array} messages 消息历史
   * @param {Object} options 可选参数
   * @returns {Promise}
   */
  async chatCompletion(messages, options = {}) {
    try {
      const response = await deepseekApi.post('/chat/completions', {
        model: options.model || 'deepseek-chat',
        messages,
        temperature: options.temperature || 0.7,
        max_tokens: options.max_tokens || 2000,
        ...options
      });
      return response.data;
    } catch (error) {
      console.error('DeepSeek API Error:', error);
      throw error;
    }
  },

  /**
   * 流式聊天（使用WebSocket）
   * @param {Array} messages 消息历史
   * @param {Function} onMessage 接收消息的回调
   * @param {Object} options 可选参数
   */
  streamChat(messages, onMessage, options = {}) {
    return new Promise((resolve, reject) => {
      const socket = new WebSocket(`wss://api.deepseek.com/v1/chat/stream`);

      socket.onopen = () => {
        socket.send(JSON.stringify({
          model: options.model || 'deepseek-chat',
          messages,
          stream: true,
          ...options
        }));
      };

      socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        onMessage(data);
      };

      socket.onclose = () => {
        resolve();
      };

      socket.onerror = (error) => {
        reject(error);
      };
    });
  }
};
